//请求用
var proto_request = {};
//请求用
var proto_field_request = {};
//编辑用
var editmodel = [];
//表格用
var tablelist = [];
//穿越用
var protofeild = []


$.ajax({
	url: 'http://' + ipm + ':8081/dict/query',
	type: 'POST',
	contentType: 'application/json',
	dataType: 'json',
	data: {},
	success: function (response) {
		console.log(response);
		protoRead(response);
		createProtofieldobj(response);
		console.log(protofeild);
		createTransfer();
	}
});

function refreshTab() {
	$.ajax({
		url: 'http://' + ipm + ':8081/dict/query',
		type: 'POST',
		contentType: 'application/json',
		dataType: 'json',
		data: {},
		success: function (response) {
			console.log(response);
			tablelist = [];
			protoRead(response);
			createTransfer();
		}
	});
}




function createTab() {
	$("#table_page").bootstrapTable('destroy');
	$("#table_page").bootstrapTable({
		data: tablelist,
		dataType: 'json',
		//method: 'POST',                      //请求方式（*）
		//toolbar: '#toolbar',              //工具按钮用哪个容器
		striped: true,                      //是否显示行间隔色
		cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
		pagination: true,                   //是否显示分页（*）
		sortable: true,                     //是否启用排序
		sortOrder: "asc",                   //排序方式
		sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
		pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
		pageSize: 10,                     //每页的记录行数（*）
		pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
		search: false,                      //是否显示表格搜索
		strictSearch: true,
		//showColumns: true,                  //是否显示所有的列（选择显示的列）
		//showRefresh: true,                  //是否显示刷新按钮
		minimumCountColumns: 1,             //最少允许的列数
		clickToSelect: true,                //是否启用点击选中行
		//height: 500,                      //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
		uniqueId: "name",                     //每一行的唯一标识，一般为主键列
		//showToggle: true,                   //是否显示详细视图和列表视图的切换按钮
		cardView: false,                    //是否显示详细视图
		detailView: true,                  //是否显示父子表
		detailFormatter: detailFormatter,
		//得到查询的参数

		queryParams: function (params) {
			//这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
			var temp = {
				rows: params.limit,                         //页面大小
				page: (params.offset / params.limit) + 1,   //页码
				sort: params.sort,      //排序列名  
				sortOrder: params.order //排位命令（desc，asc） 
			};
			return temp;
		},

		columns: [{
			field: 'name',
			title: '协议名'
		}, {
			field: 'segment_list_num',
			title: '字段个数'
		},
		// {
		// 	field: 'segment_tag',
		// 	title: '标签个数',

		// },
		//  {
		// 	field: 'ID',
		// 	title: '编辑标签',
		// 	width: 120,
		// 	align: 'center',
		// 	valign: 'middle',
		// 	formatter: actionFormatter
		// }, 
		{
			field: 'name',
			title: '删除',
			width: 120,
			align: 'center',
			valign: 'middle',
			formatter: actionFormatterD
		},
		],
		onLoadSuccess: function () {
		},
		onLoadError: function () {
			showTips("数据加载失败！");
		},
		onDblClickRow: function (row, $element) {
			var id = row.ID;
			EditViewById(id, 'view');
		},

	});
}

//细节展示
function detailFormatter(index, row) {
	var html = [];
	$.each(row, function (key, value) {
		if (key == "segment_list") {
			html.push('<p>字段详情</p>');
			for (var i = 0; i < value.length; i++) {
				for (var j = 0; j < protofeild.length; j++) {
					if (value[i] == protofeild[j].id) {
						if (protofeild[j].method == "dict_name") {
							html.push('<p>名称：' + protofeild[j].name + ' , 类型：' + protofeild[j].value_type + ' , 长度：' + protofeild[j].value_length + ' , 字典：' + protofeild[j].value + ' , 数据库表字段：' + protofeild[j].dbfield + ' </p>');
						} else if (protofeild[j].method == "logical_expressions") {
							html.push('<p>名称：' + protofeild[j].name + ' , 类型：' + protofeild[j].value_type + ' , 长度：' + protofeild[j].value_length + ' , 逻辑表达式：' + protofeild[j].value + ' , 数据库表字段：' + protofeild[j].dbfield + ' </p>');
						} else if (protofeild[j].method == "parse_list_name") {
							html.push('<p>名称：' + protofeild[j].name + ' , 类型：' + protofeild[j].value_type + ' , 长度：' + protofeild[j].value_length + ' , 解析表：' + protofeild[j].value + ' , 数据库表字段：' + protofeild[j].dbfield + ' </p>');

						} else if (protofeild[j].method == "string") {
							if (protofeild[j].value == "ascii") {
								html.push('<p>名称：' + protofeild[j].name + ' , 类型：' + protofeild[j].value_type + ' , 长度：' + protofeild[j].value_length + ' , 字符串：' + protofeild[j].value + ' , 数据库表字段：' + protofeild[j].dbfield + ' </p>');
							} else if (protofeild[j].value == "hex") {
								html.push('<p>名称：' + protofeild[j].name + ' , 类型：' + protofeild[j].value_type + ' , 长度：' + protofeild[j].value_length + ' , 原始值：' + protofeild[j].value + ' , 数据库表字段：' + protofeild[j].dbfield + ' </p>');
							}
						} else if (protofeild[j].method == "strtrim") {
							html.push('<p>名称：' + protofeild[j].name + ' , 类型：' + protofeild[j].value_type + ' , 长度：' + protofeild[j].value_length + ' , 分隔符：' + protofeild[j].value + ' , 数据库表字段：' + protofeild[j].dbfield + ' </p>');
						} else if (protofeild[j].method == "bits") {
							html.push('<p>名称：' + protofeild[j].name + ' , 类型：' + protofeild[j].value_type + ' , 长度：' + protofeild[j].value_length + ' , 比特位：' + protofeild[j].value + ' , 数据库表字段：' + protofeild[j].dbfield + ' </p>');
						}

					}
				}
			}
		}
	});
	return html.join('');
}


// function protoSegmentInfo(index, oProtofeild) {
// 	for(var i = 0 ; i < protofeild.length; i++){
// 		if(index == protofeild[i].id){
// 			oProtofeild = protofeild[i];
// 			return;
// 		}
// 	}
// }

// function detailFormatter(index, row) {
// 	var html = [];
// 	$.each(row, function(key, value) {
// 		if(key != "segment_list"){
// 			return;
// 		}

// 		for(var i = 0 ; i < value.length; i++){
// 			var oProtofeild;
// 			protoSegmentInfo(value[i], oProtofeild);
// 			html.push('<p>名称：' + oProtofeild.name + ' 类型：' + value[0] + ' 长度：' + value[0] + ' </p>');
// 		}
// 		//html.push('<p><b>' + key + ':</b> ' + value[0] + '</p>');

// 	});
// 	return html.join('');
// }

function actionFormatter(value, row, index) {
	var id = value;
	var result = "";
	result += "<a href='javascript:;' class='btn btn-xs blue' onclick=\"EditProtoById('" + id + "')\" title='编辑'><span class='feather-edit'></span></a>";
	// result += "<a href='javascript:;' class='btn btn-xs blue' onclick=\"EditViewById('" + id + "')\" title='编辑'><span class='feather-edit'></span></a>";

	return result;
}
function actionFormatterD(value, row, index) {
	var id = value;
	var result = "";
	result += "<a href='javascript:;' class='btn btn-xs red' onclick=\"Proto_modify('" + id + "')\" title='删除'><span class='feather-trash-2'></span></a>";
	return result;
}


//新增协议字段
function createProtoModel() {
	$('#protoModal').modal('show');

}

layui.config({
	base: 'step-lay/'
}).use(['form', 'step'], function () {
	var $ = layui.$
		, form = layui.form
		, step = layui.step;

	step.render({
		elem: '#stepForm',
		filter: 'stepForm',
		width: '100%', //设置容器宽度
		stepWidth: '750px',
		height: '500px',
		stepItems: [{
			title: '第一步'
		}, {
			title: '第二步'
		}, {
			title: '完成'
		}]
	});


	form.on('submit(formStep)', function (data) {
		step.next('#stepForm');
		return false;
	});

	form.on('submit(formStep2)', function (data) {
		step.next('#stepForm');
		return false;
	});

	$('.pre').click(function () {
		step.pre('#stepForm');
	});

	$('.next').click(function () {
		step.next('#stepForm');
	});
})

var field
var transferIdGroup = []
layui.use('form', function () {
	var form = layui.form;
	//方法提交
	$('#testSubmitBtn').on('click', function (data) {
		form.submit('proto', function (data) { // 注：v2.7.0 新增
			// 回调函数返回结果跟上述 submit 事件完全一致
			field = data.field;
			console.log(data.field)
			// do something
			protoJson();
		});
		return false;
	});


});



//模态框关闭清理
$('#myModal').on('hidden.bs.modal', function () {
	deleteprotoViewEdit();
});

//模态框清理函数
function deleteprotoViewEdit() {
	var Table = document.getElementById("protoView");
	var rows = Table.getElementsByTagName("tr").length;
	var rowsNum = 0;
	for (rowsNum; rowsNum < rows - 1; rowsNum++) {
		NewRow = Table.deleteRow(-1); //添加
	}
}







function createTransfer() {
	var segment_transfer = []
	for (var i = 0; i < protofeild.length; i++) {
		var obj = {
			"value": ""
			, "title": ""
		}
		var method
		if (protofeild[i].method == "dict_name") {
			method = "字典";
		} else if (protofeild[i].method == "logical_expressions") {
			method = "逻辑表达式";
		} else if (protofeild[i].method == "parse_list_name") {
			method = "解析表";
		} else if (protofeild[i].method == "string" && protofeild[i].value == "ascii") {
			method = "字符串";
		} else if (protofeild[i].method == "string" && protofeild[i].value == "hex") {
			method = "原始值";
		} else if (protofeild[i].method == "strtrim") {
			method = "分隔符";
		}
		var segment_title = protofeild[i].ID + "|" + protofeild[i].name + "|" + protofeild[i].value_type + "|" + protofeild[i].value_length + "|" + method + "|" + protofeild[i].value;
		obj.value = protofeild[i].id;
		obj.title = segment_title;
		segment_transfer.push(obj);
	}
	console.log(segment_transfer);
	layui.use(['transfer', 'layer', 'util'], function () {
		var $ = layui.$
			, transfer = layui.transfer
			, layer = layui.layer
			, util = layui.util;
		//基础效果
		transfer.render({
			elem: '#test1'
			, data: segment_transfer
			, id: 'key123'
			, title: ['待选字段', '已选字段']
			, showSearch: true
			, width: 300 //定义宽度
			, height: 350 //定义高度
		})
		//批量办法定事件
		util.event('lay-demoTransferActive', {
			getData: function (othis) {
				transferIdGroup = []
				var getData = transfer.getData('key123'); //获取右侧数据
				//layer.alert(JSON.stringify(getData));
				for (var i = 0; i < getData.length; i++) {
					transferIdGroup.push(getData[i].value);
				}
				console.log(transferIdGroup);
			}
		});
	});
}


//创建一个协议JSON
function protoJson() {
	var arr = proto_request.protocols;
	if (arr) {//如果有数据
		var protoWeb = {
			"cfgType": "4",
			//"cfgName": "",
			"cfgName": "proto_cfg.json",
			"content": "",
			// "syncNodes": ""
		}
		var protoSave = {
			"cfg_type": 4,
			"protocols": ""
		}
		var proto = {
			"name": "",
			"segment_list": "",
			"segment_tag": ""
		}

		proto.name = field.name;
		proto.segment_list = transferIdGroup;
		proto.segment_tag = [];
		arr.push(proto);
		protoSave.protocols = arr;
		protoWeb.content = JSON.stringify(protoSave);
		postQuestSave(protoWeb);
		alert("新增成功！");
		//refreshTab();
		window.location.reload();
	} else {//如果没有数据
		arr = []
		var protoWeb = {
			"cfgType": "4",
			"cfgName": "proto_cfg.json",
			"content": "",
			// "syncNodes": ""
		}
		var protoSave = {
			"cfg_type": 4,
			"protocols": ""
		}
		var proto = {
			"name": "",
			"segment_list": "",
			"segment_tag": ""
		}

		proto.name = field.name;
		proto.segment_list = transferIdGroup;
		proto.segment_tag = [];
		arr.push(proto);
		protoSave.protocols = arr;
		protoWeb.content = JSON.stringify(protoSave);
		postQuestSave(protoWeb);
		alert("新增成功！");
		//refreshTab();
		window.location.reload();
	}

}


//删除协议JSON
function Proto_modify(args) {
	// var arrProto = proto_request.protocols;
	// if (arrProto.length < 2) {
	// 	alert('请勿全部删除');
	// 	return false;
	// }
	var arrProtoWeb = []
	var protoWeb = {
		"cfgType": 4,
		"deletedName": ""
	}
	protoWeb.deletedName = args;
	arrProtoWeb.push(protoWeb)
	sss = JSON.stringify(arrProtoWeb)
	console.log(sss)

	$.ajax({
		url: 'http://' + ipm + ':8081/dict/deleteProto',
		type: 'POST',
		contentType: 'application/json',
		dataType: 'json',
		data: sss,
		success: function (response) {
			console.log(response);
		}
	});
	window.location.reload();
}

// //协议字段，删除函数
// function DeleteProtoByIds(args) {
// 	var arrProto = proto_request.protocols;
// 	if (arrProto.length < 2) {
// 		alert('请勿全部删除');
// 		return false;
// 	}
// 	for (var i = 0; i < arrProto.length; i++) {
// 		if (arrProto[i].name == args) {
// 			arrProto.splice(i, 1);
// 		}
// 	}
// 	console.log(arrProto);
// 	var protoWeb = {
// 		"cfgType": "4",
// 		"content": ""
// 	}
// 	var protoSave = {
// 		"cfg_type": 4,
// 		"protocols": ""
// 	}
// 	protoSave.protocols = arrProto;
// 	protoWeb.content = JSON.stringify(protoSave)
// 	postQuestSave(protoWeb);
// 	//refreshTab();
// 	window.location.reload();
// }

console.log(tablelist);
var protonameroom
//根据ID获取对应内容
function EditProtoById(args) {
	$('#myModal').modal('show');
	//$('#protoEditer').modal('show');

	//----获取下拉框信息----
	var segment_transfer = []
	for (var i = 0; i < protofeild.length; i++) {
		var obj = {
			"value": ""
			, "title": ""
		}
		var method
		if (protofeild[i].method == "dict_name") {
			method = "字典";
		} else if (protofeild[i].method == "logical_expressions") {
			method = "逻辑表达式";
		} else if (protofeild[i].method == "parse_list_name") {
			method = "解析表";
		} else if (protofeild[i].method == "string" && protofeild[i].value == "ascii") {
			method = "字符串";
		} else if (protofeild[i].method == "string" && protofeild[i].value == "hex") {
			method = "原始值";
		} else if (protofeild[i].method == "strtrim") {
			method = "分隔符";
		}
		var segment_title = protofeild[i].name + "|" + protofeild[i].value_type + "|" + protofeild[i].value_length + "|" + method + "|" + protofeild[i].value;
		obj.value = protofeild[i].id;
		obj.title = segment_title;
		segment_transfer.push(obj);
	}
	var selectOption = [];
	var tableArr = tablelist[args - 1].segment_list;
	var tagA = proto_request.protocols;
	var tagArr = tagA[args - 1].segment_tag;
	console.log(segment_transfer);
	console.log(tableArr);
	console.log(tagArr);
	for (var i = 0; i < tableArr.length; i++) {
		for (var j = 0; j < segment_transfer.length; j++) {
			if (tableArr[i] == segment_transfer[j].value) {
				for (var k = 0; k < tagArr.length; k++) {
					if (tableArr[i] == tagArr[k].id) {
						selectOption[k] += "<option selected value = " + segment_transfer[j].value + ">" + segment_transfer[j].title + "</option>";
					} else {
						selectOption[k] += "<option value = " + segment_transfer[j].value + ">" + segment_transfer[j].title + "</option>";
					}
				}
			}
		}
	}
	//----获取下拉框信息结束----


	currentId = args - 1;
	protonameroom = tablelist[args - 1].name;
	var Table = document.getElementById("protoView");
	for (var rowsNum = 0; rowsNum < editmodel[args - 1].length; rowsNum++) {
		if (editmodel[args - 1].length > 0) {
			//console.log(editmodel[args - 1].length);
			NewRow = Table.insertRow(); //添加行
			//添加列
			id = NewRow.insertCell();
			tag = NewRow.insertCell();
			operate = NewRow.insertCell();
			//属性赋值
			id.innerHTML = '<select id = id" + rowsNum + 1 + " Name=id" + rowsNum + 1 + " class="form-control form-control-sm"> ' + selectOption[rowsNum] + ' </select>'
			tag.innerHTML = "<input id = tag" + rowsNum + 1 + " Name=tag" + rowsNum + 1 + " value=" + editmodel[args - 1][rowsNum].tag.toString(16) + " class='form-control form-control-sm' type='text' />";
			operate.innerHTML = '<div id=operate' + (rowsNum + 1) + '><a style="cursor:pointer;color:#007bff;"  onclick="deleteInterfaceParam(' + (args - 1) + ');">取消</a></div>';

		}
	}

}


//插入一行tag
function addprotoEditTable() {
	var Table = document.getElementById("protoView");
	//addId++;
	//----获取下拉框信息----
	var segment_transfer = []
	for (var i = 0; i < protofeild.length; i++) {
		var obj = {
			"value": ""
			, "title": ""
		}
		var method
		if (protofeild[i].method == "dict_name") {
			method = "字典";
		} else if (protofeild[i].method == "logical_expressions") {
			method = "逻辑表达式";
		} else if (protofeild[i].method == "parse_list_name") {
			method = "解析表";
		} else if (protofeild[i].method == "string" && protofeild[i].value == "ascii") {
			method = "字符串";
		} else if (protofeild[i].method == "string" && protofeild[i].value == "hex") {
			method = "原始值";
		} else if (protofeild[i].method == "strtrim") {
			method = "分隔符";
		}
		var segment_title = protofeild[i].name + "|" + protofeild[i].value_type + "|" + protofeild[i].value_length + "|" + method + "|" + protofeild[i].value;
		obj.value = protofeild[i].id;
		obj.title = segment_title;
		segment_transfer.push(obj);
	}
	var selectAddOption = "";
	var tableArr = tablelist[currentId].segment_list;
	for (var i = 0; i < tableArr.length; i++) {
		for (var j = 0; j < segment_transfer.length; j++) {
			if (tableArr[i] == segment_transfer[j].value) {
				selectAddOption += "<option value = " + segment_transfer[j].value + ">" + segment_transfer[j].title + "</option>";
			}
		}
	}
	//----获取下拉框信息结束----

	var rowsNum = Table.rows.length - 1;
	NewRow = Table.insertRow(); //添加行
	//添加列
	id = NewRow.insertCell();
	tag = NewRow.insertCell();
	operate = NewRow.insertCell();

	//属性赋值
	id.innerHTML = '<select id = id" + rowsNum + 1 + " Name=id" + rowsNum + 1 + " class="form-control form-control-sm"> ' + selectAddOption + ' </select>'

	//	id.innerHTML = "<input id = id" + rowsNum + 1 + " Name=id" + rowsNum + 1 + " class='form-control form-control-sm'  type='text' />";
	tag.innerHTML = "<input id = tag" + rowsNum + 1 + " Name=tag" + rowsNum + 1 + " class='form-control form-control-sm'  type='text' />";
	operate.innerHTML = '<div id=operate' + (rowsNum + 1) + '><a style="cursor:pointer;color:#007bff;"  onclick="deleteInterfaceParam();">取消</a></div>';

}

//删除编辑中的tag字段
function deleteInterfaceParam() {
	var td = event.srcElement; // 通过event.srcElement 获取激活事件的对象 td
	var key = td.parentElement.parentElement.parentNode.rowIndex;  //获取行索引
	document.getElementById("protoView").deleteRow(key); //删除
	//addId--;
}



//一个协议tag修改JSON
function buildEditProtoJson() {
	var register = $("#protoForm1");
	var formData = register.serializeArray();
	var arrProto = proto_request.protocols;
	var protoWeb = {
		"cfgType": "4",
		//"cfgName": "",
		"cfgName": "proto_cfg.json",
		"content": "",
		// "syncNodes": ""
	}
	var protoSave = {
		"cfg_type": 4,
		"protocols": ""
	}
	var json = []
	var arr = []
	for (var i = 0; i < arrProto.length; i++) {
		if (arrProto[i].name == protonameroom) {
			for (var j = 0; j < formData.length; j++) {
				var obj = {}

				formData[j].name = "id";
				formData[j + 1].name = "tag";
				obj[formData[j].name] = parseInt(formData[j]['value']);
				// if (parseInt(formData[j + 1]['value'], 16)) {
				// 	return true
				// } else if (parseInt(formData[j + 1]['value'], 16) == "") {
				// 	alert("0")
				// 	return false;
				// }
				console.log(isHexadecimal(formData[j + 1]['value']))
				if (isHexadecimal(formData[j + 1]['value']) == false) {
					alert("修改失败,请输入16进制数")
					return false;
				}
				// console.log(parseInt(formData[j + 1]['value'], 16))
				obj[formData[j + 1].name] = parseInt(formData[j + 1]['value'], 16);
				json.push(obj);
				j++;
			}
			console.log(json);
			arrProto[i].segment_tag = json;
			arr.push(arrProto[i]);
		} else {
			arr.push(arrProto[i]);
		}
	}
	console.log(arr);
	protoSave.protocols = arr;
	protoWeb.content = JSON.stringify(protoSave);
	console.log(protoWeb);
	postQuestSave(protoWeb);
	//refreshTab();
	window.location.reload();
}


//判断是否是16进制数
function isHexadecimal(str) {
	var pattern = /^[0-9a-fA-F]+$/; // 定义只包含十六进制字符的正则表达式
	return pattern.test(str); // 返回结果
}